
using RobotInspection.Interfaces;
using RobotInspection.Services; // 添加点检计划服务命名空间
using SqlSugar;
using Serilog;
using System.Reflection;
using System.Text.Json.Serialization.Metadata;
using _RobotInspection.Middlewares;
using _RobotInspection.Swagger;
using _RobotInspection.Interfaces;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using _RobotInspection.Extensions;
using _RobotInspection.Services;
using _RobotInspection.Repositories; // 添加中间件命名空间引用

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
// 配置 Serilog  
// 使用 appsettings.json 中的配置来配置 Serilog  
Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration) // 从配置读取  
    .CreateLogger();
builder.Host.UseSerilog();

//注入Sqlsugar服务
builder.Services.AddSqlsugarSetup(builder.Configuration, "db_master");
// 通过接口注入 Repository
builder.Services.AddScoped<IRepository, Repository>();
// 通过接口注入 Service
builder.Services.AddScoped<IService, Service>();
// 通过接口注入 UserService
builder.Services.AddScoped<IUserService, UserService>();
// 通过接口注入 EquipmentService
builder.Services.AddScoped<IEquipmentService, EquipmentService>();
// 通过接口注入 EquipmentService
builder.Services.AddScoped<IInspectionItemService, InspectionItemService>();
// 通过接口注入 AttentionItemService
builder.Services.AddScoped<IAttentionItemService, AttentionItemService>();
// 通过接口注入 RepairPlanService
builder.Services.AddScoped<IRepairPlanService, RepairPlanService>();
// 注入点检计划服务（接口注入）
builder.Services.AddScoped<IInspectionPlanService, InspectionPlanService>();
// 注入点检记录自动生成服务
builder.Services.AddScoped<IInspectionRecordGeneratorService, InspectionRecordGeneratorService>();
builder.Services.AddScoped<IDailyInspectionManagementService, DailyInspectionManagementService>();


// 注册 SocketService 服务
//builder.Services.AddSingleton<SocketService>();
//注册MqttService服务
//builder.Services.AddSingleton<MqttService>();
//注册WebSocketService服务
//builder.Services.AddSingleton<WebSocketService>();

// 允许跨源请求（CORS）  
// 仅当你的API需要被浏览器中的其它应用（如前端）访问时  
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", builder =>
    {
        builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
    });
});
// 配置路由为小写+连字符风格 RESTful API 路由命名
builder.Services.AddRouting(options =>
{
    options.LowercaseUrls = true;
    options.LowercaseQueryStrings = true; // 可选
});
// 使用自定义的路由参数转换器（KebabCase）
builder.Services.AddControllers(options =>
{
    options.Conventions.Add(new RouteTokenTransformerConvention(new KebabCaseParameterTransformer()));
});

//swagger 文档说明
builder.Services.AddSwaggerGen(options =>
{

    var xmlFileName = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";

    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFileName), true);

    //  注册自定义过滤器：显示接口状态
    options.OperationFilter<ApiStatusOperationFilter>();
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
#region 启动 Socket 服务
//try
//{
//    var socketService = app.Services.GetRequiredService<SocketService>();
//    socketService.Start(5000); // 设置监听端口为 5000
//}
//catch (Exception ex)
//{
//    Log.Error(ex, "Socket 服务启动失败");
//}
#endregion
// 启动文件监控服务
//try
//{
//    var fileWatcherService = app.Services.GetRequiredService<FileWatcherService>();
//    fileWatcherService.StartWatching(@"D:\SH\image", "*.*"); // 监控的路径和文件筛选器
//}
//catch (Exception ex)
//{
//    Log.Error(ex, "文件监控服务启动失败");
//}
#region 数据库生成实体

// 生成实体类
//using (var scope = app.Services.CreateScope())
//{
//    var db = scope.ServiceProvider.GetRequiredService<ISqlSugarClient>();
//    var generator = new EntityGenerator(db);



//    // 指定要生成的表名和数据库
//    var configId = "db_master"; // 指定数据库的ConfigId，与SqlsugarSetup.cs中配置的一致

//    var outputPath = @"D:\SH\项目\1420磨床\WorkerService - 副本\WorkerService\Entities\";

//    //// 方式1：生成指定表的实体
//    // var tableNames = new string[] { "IHDHistory" };
//    //foreach (var tableName in tableNames)
//    //{
//    //    generator.GenerateEntityFromSpecificDb(configId, tableName, outputPath);
//    //}

//    // 方式2：生成所有表的实体
//    generator.GenerateAllEntitiesFromSpecificDb(configId, outputPath, "WorkerService.Entities");
//}

#endregion

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())//检查是否属于开发环境
{

}
app.UseMiddleware<GlobalExceptionMiddleware>(); // 添加全局异常处理中间件
app.UseSwagger();
app.UseSwaggerUI();

app.UseCors("AllowAll"); // 使用CORS策略 
app.UseStaticFiles(); // 启用wwwroot静态文件服务
app.UseAuthorization();
app.MapControllers();

app.Run();
